package com.hsy.crm.web.service.impl;

import com.hsy.crm.web.domain.cm.Unified;
import com.hsy.crm.web.domain.entity.Dict;
import com.hsy.crm.web.domain.entity.PlatformCustomer;
import com.hsy.crm.web.domain.entity.User;
import com.hsy.crm.web.domain.ex.ServiceException;
import com.hsy.crm.web.domain.vo.platform.CreateVo;
import com.hsy.crm.web.domain.vo.platform.RegCodeVo;
import com.hsy.crm.web.domain.vo.platform.SchemaVo;
import com.hsy.crm.web.mapper.DictMapper;
import com.hsy.crm.web.mapper.PlatCustomerMapper;
import com.hsy.crm.web.mapper.SchemaMapper;
import com.hsy.crm.web.mapper.UserMapper;
import com.hsy.crm.web.service.asyn.SchemaService;
import com.hsy.crm.web.service.base.BaseService;
import com.hsy.crm.web.utils.DateUtils;
import com.hsy.crm.web.utils.DictUtils;
import com.hsy.crm.web.utils.Md5Utils;
import com.hsy.crm.web.utils.RandomUtils;
import com.hsy.crm.web.utils.ServiceUtils;
import com.hsy.crm.web.utils.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 平台客户服务
 */
@Service
public class PlatCustomerService extends BaseService<PlatformCustomer> {

    @Autowired
    PlatCustomerMapper platCustomerMapper;

    @Autowired
    DictMapper dictMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    SchemaService schemaService;

    @Autowired
    SchemaMapper schemaMapper;

    private static final long BASE_TIME = DateUtils.parseShort("20191212").getTime();

    @Transactional
    public Unified<String> create(CreateVo createVo){
        PlatformCustomer platformCustomer = new PlatformCustomer();
        platformCustomer.setPlatCustomerId(createVo.getRandomId());
        platformCustomer = schemaMapper.findPlatformCustomer(platformCustomer);
        String customerId = platformCustomer.getPlatCustomerId();

        //update platform company info
        platformCustomer.setCompanyName(createVo.getCompanyName());
        platformCustomer.setIndustryType(createVo.getIndustryType());
        platCustomerMapper.updateComInfo(platformCustomer);

        //init dict
        List<Dict> dicts = platCustomerMapper.findS1dDicts();
        for( Dict dict : dicts ){
            dict.setId(UuidUtils.getUuid());
            dict.setCustomerId(customerId);
        }
        platCustomerMapper.insertDicts(dicts);
        DictUtils.setDicts(customerId,dicts);

        //init print

        // create tables
        schemaService.init(customerId,SchemaService.init_type);

        // style table data call schemaService.init_style_data
        SchemaVo schemaVo = new SchemaVo();
        schemaVo.setCustomerId(customerId);
        schemaVo.setLoginUserId(0L);
        schemaService.init_style_data(schemaVo);
        return Unified.newInstance();
    }

    /**
     * 注册
     */
    @Transactional
    public Unified<String> regedit(RegCodeVo regCodeVo){
        Unified<String> unified = new Unified<>();
        Long platformCustomerId = checkPhone(regCodeVo.getPhone());
        if( platformCustomerId != null ){
            unified.setResult(-101);
            return unified;
        }

        PlatformCustomer platformCustomer = this.insertPlatCustomer(regCodeVo);
        unified.setData(platformCustomer.getPlatCustomerId());

        //init user
        this.insertUser(regCodeVo,platformCustomer.getPlatCustomerId());

        return unified;
    }

    private void insertUser(RegCodeVo regCodeVo,String customerId){
        User user = new User();
        user.setId(UuidUtils.getUuid());
        user.setUsername(regCodeVo.getPhone());
        user.setPassword(Md5Utils.encrypt(regCodeVo.getPassword()));
        user.setName("管理员");
        user.setPhone(regCodeVo.getPhone());
        user.setCompanyId(0L);
        user.setLoginUserId(0L);
        user.setCustomerId(customerId);
        ServiceUtils.init_entity_insert(user);
        platCustomerMapper.insertUser(user);
    }

    private String getPlatCustomerId(){

        for( int i=0 ; i<100 ; i++ ){
            String code = RandomUtils.randomCode(3);
            PlatformCustomer platformCustomer = new PlatformCustomer();
            platformCustomer.setPlatCustomerId(code);
            Long id = platCustomerMapper.checkPlatCustomerId(platformCustomer);
            if( id == null ){
                return code;
            }
        }

        return null;
    }

    private PlatformCustomer insertPlatCustomer(RegCodeVo regCodeVo){
        PlatformCustomer platformCustomer = new PlatformCustomer();
        String platCustomerId = getPlatCustomerId();
        if( platCustomerId == null ){
            throw new ServiceException("plat customer code error");
        }

        platformCustomer.setPlatCustomerId(platCustomerId);
        platformCustomer.setContactPhone(regCodeVo.getPhone());
        platformCustomer.setUserNumber(1);
        platformCustomer.setExpiryTime((int)(System.currentTimeMillis()-BASE_TIME));

        this.insert(platformCustomer);
        return platformCustomer;
    }

    private Long checkPhone(String phone){
        PlatformCustomer platformCustomer = new PlatformCustomer();
        platformCustomer.setContactPhone(phone);
        return platCustomerMapper.checkPhone(platformCustomer);
    }

}
